JavaScript
CSCE 242
University of South Carolina
José M. Vidal [1]
http://jmvidal.cse.sc.edu/talks/javascript/ [2]
An introduction to the language. This talk follows:
Examples are
taken [5] from Flanagan.
1 Introduction
- JavaScript [6] resides on your browser.
- JavaScript has nothing to do with Java
- JavaScript is not a scripting language.
- JavaScript is object-oriented, but without classes.
- JavaScript is an instance of ECMAScript, ActionScript (MacroMedia Flash) is another.
- JavaScript is used in DreamWeaver, Photoshop, PDF files,
Dashboard.
- JavaScript can be used by
itself [7] or embedded: SpiderMonkey [8],
Rhino [9].
- Chrome [10] and firefox 3.1 [11] compile JavaScript: 20 to 40 times faster!
1.1 Example
This code:
<html>
<head><title>Factorials</title></head>
<body>
<h2>Table of Factorials</h2>
<script>
</script>
</body>
</html>
Looks like
this.
- Note that
document.write
does not work with XHTML.
1.2 Another Example
<html>
<head>
<title>JavaScript Loan Calculator</title>
<style>
.result { font-weight: bold; } /* For elements with class="result" */
#payment { text-decoration: underline; } /* For element with id="payment" */
</style>
</head>
<body>
<form name="loandata">
<table>
<tr><td><b>Enter Loan Information:</b></td></tr>
<tr>
<td>1) Amount of the loan (any currency):</td>
<td><input type="text" name="principal" onchange="calculate();"></td>
</tr>
<tr>
<td>2) Annual percentage rate of interest:</td>
<td><input type="text" name="interest" onchange="calculate();"></td>
</tr>
<tr>
<td>3) Repayment period in years:</td>
<td><input type="text" name="years" onchange="calculate();"></td>
</tr>
<tr><td></td>
<td><input type="button" value="Compute" onclick="calculate();"></td>
</tr>
<tr><td><b>Payment Information:</b></td></tr>
<tr>
<td>4) Your monthly payment:</td>
<td>$<span class="result" id="payment"></span></td>
</tr>
<tr>
<td>5) Your total payment:</td>
<td>$<span class="result" id="total"></span></td>
</tr>
<tr>
<td>6) Your total interest payments:</td>
<td>$<span class="result" id="totalinterest"></span></td>
</tr>
</table>
</form>
<script language="JavaScript">
/*
* This is the JavaScript function that makes the example work. Note that
* this script defines the calculate() function called by the event
* handlers in the form. The function reads values from the form
* <input> fields using the names defined in the HTML code above. It outputs
* its results into the named <span> elements.
*/
function calculate() {
// Get the user's input from the form. Assume it is all valid.
// Convert interest from a percentage to a decimal, and convert from
// an annual rate to a monthly rate. Convert payment period in years
// to the number of monthly payments.
var principal = document.loandata.principal.value;
var interest = document.loandata.interest.value / 100 / 12;
var payments = document.loandata.years.value * 12;
// Now compute the monthly payment figure, using esoteric math.
var x = Math.pow(1 + interest, payments);
var monthly = (principal*x*interest)/(x-1);
// Get named <span> elements from the form.
var payment = document.getElementById("payment");
var total = document.getElementById("total");
var totalinterest = document.getElementById("totalinterest");
// Check that the result is a finite number. If so, display the
// results by setting the HTML content of each <span> element.
if (isFinite(monthly)) {
payment.innerHTML = monthly.toFixed(2);
total.innerHTML = (monthly * payments).toFixed(2);
totalinterest.innerHTML = ((monthly*payments)-principal).toFixed(2);
}
// Otherwise, the user's input was probably invalid, so display nothing.
else {
payment.innerHTML = "";
total.innerHTML = ""
totalinterest.innerHTML = "";
}
}
</script>
</body>
</html>
Results in
this.
2 Lexical Structure
- Looks like C.
- Case-sensitive.
- Ignores spaces.
- Semicolons optional, but use them;
3 Datatypes and Values
- Numbers
- Strings
- Booleans
null
is "no value"
undefined
is for declared but unassigned
variables. Note that null == undefined
- Objects
3.1 Numbers
- All numbers are floating point values: 0.1 + 0.2 [12]
- Can use exponential notation:
6.02E23
3.1.1 Special Numbers
NaN
: is not a number
Infinity
Number.MAX_VALUE
Number.MIN_VALUE
: closest to zero
Number.POSITIVE_INFINITY
Number.NEGATIVE_INFINITY
3.2 Strings
- "" Empty string
- 'hello'
- "hello"
- "Jim's scooter."
- '<a href="http://me.com">me</a>'
- "The End.\n"
- No character type.
3.2.1 Working with Strings
3.3 Booleans
3.4 Functions
- You can define your own functions:
function square(x) {
return x * x;
}
- Or, do it the lambda way:
var square = function (x) {return x*x};
square(5); [22]
var plusone = function (x) {return x+1};
var doublef = function (f,x) {return f(f(x))};
doublef(plusone,5) [23]
3.5 Objects
- An object is a collection of named values (a map, a
hashtable).
image.width
document.myform.button
- Create one with:
var o = new Object();
var now = new Date();
var point = {x:2.3, y:-1.2};
var rectangle =
{
upperLeft: {x:2,y:2},
lowerRight: {x:4, y:0}
};
3.6 Arrays
- Arrays are a lot like objects.
- They are also implemented as maps.
- Create them with
var a = [1, "hello", true, {x:1, y:2}, 4];
a; [24]
3.7 Date
- You can get the current time with var now = new
Date() [25]
- Or create your own time:
var bday = Date(2007, 2,
15)
bday.setFullYear(bday.getFullYear() + 1)
3.8 Regular Expressions
/^HTML/
/[1-9][0-9]*/
/\bjavascript\n/i
- more later...
3.9 Wrapper Objects
var s = "hello";
vas S = new String("hello");
3.10 Value vs Reference
- Primitive types are passed by value.
- Reference types (objects, arrays, functions) are passed
by reference.
- By value:
var n = 1; var m = n;
function add_to_total(total, x)
{
total = total + x; }
add_to_total(n, m);
if (n == 1) m = 2;
m; [26]
var xmas = new Date(2007, 11, 25);
var solstice = xmas;
solstice.setDate(21);
xmas.getDate();
(xmas == solstice)
var xmas = new Date(2007, 11, 25);
var solstice_plus_4 = new Date(2007, 11, 25);
function addToTotals(totals, x)
{
totals[0] = totals[0] + x;
totals[1] = totals[1] + x;
totals[2] = totals[2] + x;
}
var t = [1,2,3];
addToTotals(t,5);
xmas != solstice_plus_4 [27]
t; [28]
4 Variables
- Are untyped.
- Can declare and initialize on the same line:
var message = "hello";
var i=0, j=0, k=1;
- Must declare before reading (writing OK in global scope, but don't)
4.1 Scope
- Global variables have global scope.
- Local variables have function scope: there is no block-level scope.
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function nested() {
var scope = "nested scope";
alert("1-" + scope); }
nested();
scope = "local scope";
for (var i =0; i < 10; i++){
var scope = "nested scope";
}
alert("2-" + scope);
}
checkscope()
4.1.1 var Location Does Not Matter
- You can use local variable before its
declared. It will be undefined.
- But, best practice is to declare all at the start of function.
var scope = "global";
function checkloc() {
alert ("1-" + scope);
var scope = "local";
alert ("2-" + scope);
}
checkloc()
4.2 Variables as Properties
- Variables are fundamentally the same as object
properties.
- There is a global object which holds (as
properties) all global vars.
- There is a call object for local variables.
- There is an execution context in which every
function (program) executes.
- Client side JavaScript uses a global execution context to
give you access to the browser.
5 Expressions and Operators
+ - * / % ++ --
==
is equal to.
===
is identical to.
5.1 Relational Operators
< > <= >=
- Is property
in
object?
- Is object
instanceof
class constructor?
5.2 String Operators
5.3 delete Operator
- Deletes properties or objects (regardless of book).
var o = {x:1,y:2};
delete o.x;
delete o;
o;
6 If Statements
if ((a == null) || (b == "")) {
}
else if (n == 3) {
}
else {
}
6.1 Switch
function convert(x){
switch(typeof x) {
case 'number':
return x.toString(16);
case 'string':
return '"' + x + '"';
case 'boolean':
return x.toString().toUpperCase();
default:
return x.toString();
}
}
case
part can have an expression.
6.2 While
while (count < 10){
document.write(count + "<br/>");
}
do {
document.write(a[i] + "<br/>");
} while (++i < a.length);
6.3 For
for (i = 0, j = 10; i < 10; i++, j--){
sum += i * j;
};
var d = {x:1, y:2};
for (var prop in d){
alert(prop + ":" + d[prop]);
}
Run [47]
6.4 Labels and Break
function testbreak(){
outerloop:
for (var i = 0; i < 10; i++){
innerloop:
for(var j = 0; j< 10; j++){
if (j > 3) break;
if (i == 2) break innerloop;
if (i == 3) break outerloop;
alert("i=" + i + " j=" + j);
}
}
alert("Final i=" + i + " j=" + j);
}
testbreak()
6.5 Throw and Catch
- You can
throw
anything, but try to use an Error
object:
function factorial (x) {
if (x < 0) {
throw new Error("Negative argument" + x);
}
for (var f = 1; x > 1; f *= x, x--);
return f;
}
try {
}
catch (e) {
switch (e.name) {
case 'Error':
break;
default:
throw e;
}
}
finally {
}
7 Objects and Arrays
- An object is a collections of named values, as we saw before:
var o = new Object();
var now = new Date();
var point = {x:2.3, y:-1.2};
var rectangle =
{
upperLeft: {x:2,y:2},
lowerRight: {x:4, y:0}
};
7.1 Object Properties
- Properties should be an identifier, not a string or
expression:
object.property
- You can list all properties with:
function DisplayPropertyNames(o){
var names ="";
for (var name in o) {
names += name + " ";
}
alert(names);
}
DisplayPropertyNames(document)
- You can check if a property exists with:
if ("x" in o) {
o.x = 1;
}
if (o.x !== undefined) {
o.x = 1;
}
7.2 Objects as Associative Arrays
- These two lines give the same value:
object.property
object["property"]
- Using the string version allows for runtime changes.
7.3 Universal Properties and Methods
7.4 Arrays
- As we saw before, they are
really maps.
- Thus, you can do some wacky stuff:
var c = new Circle(1,2,3);
c[0] = "this is an array element of an object";
7.4.1 Array Length
7.4.2 Array Methods
join()
converts an array into a string, using a given separator:
var a =[1,2,3];
a.join('=='); [55]
reverse()
var a=[1,2,3];
a.reverse(); [56]
sort()
var a=['beta','alpha','delta'];
a.sort(); [57]
var a=[1,2,3,4];
a.sort(function(x,y){return y-x;}); [58] later...
concat(x)
concatenate with x
var a=[1,2,3];
a.concat(4,5); [59]
a.concat([4,5]); [60]
a.concat([4,5],[6,7]); [61]
a.concat(4,5,[6,[7,8]]); [62] hmmm, try in firebug.
slice(start,length)
returns a subset. Negative means start from end.
var a=[1,2,3,4,5];
a.slice(0,3); [63]
a.slice(3); [64]
a.slice(1,-1); [65]
a.slice(-3,-1); [66]
a.splice(start, length)
modifies array deleting elements:
var a=[1,2,3,4,5,6,7,8];
a.splice(4); [67]
var a=[1,2,3,4,5,6,7,8];
a.splice(1,2); [68]
var a=[1,2,3,4,5,6,7,8];
a.splice(2,4); [69]
a.push(x)
adds x
to the end and
pop()
deletes and returns the last element.
a.unshift(x)
and shift()
are the same but from the beginning.
8 Functions
- We saw before how to define
functions.
- These function literals are also known as
lambda functions.
- You can do fun stuff:
function hypotenuse(a,b){
function square(x) {
return x*x;
}
return Math.sqrt(square(a) + square(b));
}
8.1 Arguments to Functions
- If called with too many arguments, they are ignored.
- If called with too few, the extra vars are set to
undefined
.
function copyPropertyNamesToArray(o, a){
if (!a) {
a = [];
};
for (var p in o) {
a.push(p);
}
return a;
}
- Within a function
arguments
refers to the
arguments array and callee
is a property of
it.
callee
refers to the function that is
currently being executed, used in recursive lambda functions
function getArguments(){
var result = "";
for (var i =0; i< arguments.length; i++){
result += arguments[i] + " ";
}
return result;
}
function getCaller(){
return arguments.callee;
}
getArguments(1,2,3) [70]
getArguments('hi', 2) [71]
getArguments() [72]
getCaller() [73]
f = function(x) {
if (x <= 1){
return 1;
}
return x * arguments.callee(x-1);
}
8.2 Functions as Data
function add(x,y) { return x + y; }
function subtract(x,y) { return x - y; }
function multiply(x,y) { return x * y; }
function divide(x,y) { return x / y; }
function operate(operator, operand1, operand2)
{
return operator(operand1, operand2);
}
var i = operate(add, operate(add, 2, 3), operate(multiply, 4, 5));
var operators = {
add: function(x,y) { return x+y; },
subtract: function(x,y) { return x-y; },
multiply: function(x,y) { return x*y; },
divide: function(x,y) { return x/y; },
pow: Math.pow };
function operate2(op_name, operand1, operand2)
{
if (typeof operators[op_name] == "function")
return operators[op_name](operand1, operand2);
else throw "unknown operator";
}
var j = operate2("add", "hello", operate2("add", " ", "world"))
var k = operate2("pow", 10, 2)
i; [74]
j; [75]
k; [76]
8.3 Functions as Methods
- You can do
o.m = myFunction;
and then
o.m();
calls myFunction
- Its how JavaScript does OOP.
- Within a method,
this
refers to the object.
var calculator = {
operand1: 1,
operand2: 3,
compute: function () {
this.result = this.operand1 + this.operand2;
}
};
calculator.compute(); [77]
calculator.result [78]
8.4 Function Properties
- Functions are objects, thus they can have properties!
- The
length
of a function is the number of
arguments it was declared with.
function foo(x,y,z){};
foo.length [79]
8.4.1 Defining new Function Properties
- Useful when your function needs to remember state
getuid.id=0;
function getuid() {
return getuid.id++;
}
getuid() [80]
8.4.2 apply and call
- Used to invoke a function
f
as if it
were a method of object o
.
f.call(o,1,2)
f.apply(o,[1,2])
the same but arguments in list.
8.4.3 Utility Function Examples
function getPropertyNames(o) {
var r = [];
for(name in o) r.push(name);
return r;
}
function copyProperties( from, to) {
if (!to) to = {};
for(p in from) to[p] = from[p];
return to;
}
function copyUndefinedProperties( from, to) {
for(p in from) {
if (!p in to) to[p] = from[p];
}
}
function filterArray( a, predicate) {
var results = [];
var length = a.length; for(var i = 0; i < length; i++) {
var element = a[i];
if (predicate(element)) results.push(element);
}
return results;
}
function mapArray(a, f) {
var r = []; var length = a.length; for(var i = 0; i < length; i++) r[i] = f(a[i]);
return r;
}
function bindMethod( o, f) {
return function() { return f.apply(o, arguments) }
}
function bindArguments( f ) {
var boundArgs = arguments;
return function() {
var args = [];
for(var i = 1; i < boundArgs.length; i++) args.push(boundArgs[i]);
for(var i = 0; i < arguments.length; i++) args.push(arguments[i]);
return f.apply(this, args);
}
}
8.5 Scoping
- Functions in JavaScript are lexically
scoped.
- Like Java, like most languages.
- Thus, this works:
function hypotenuse(a,b){
function squarea() {
return a*a;
}
function squareb() {
return b*b;
}
return Math.sqrt(squarea() + squareb());
}
hypotenuse(2,2); [81]
8.5.1 Call Object as Namespace
- When a function is invoked a call object is
created which stores arguments and local variables.
- This call object can be used as a namespace:
(function () { var a = 123; var b = 'hello';
})();
8.5.2 Closures
- In a closure we use the function as data and rely
on lexical scoping to give more information to this function:
var x = "global";
function f() {
var x = "local";
function g() { alert(x);
};
return g();
}
x; [82]
f(); [83]
- That might not appear surprising, but how about this?
var x = "global";
function f2() {
var x = "local";
function g() { alert(x);
};
return g;
}
var g = f2();
x; [84]
g(); [85]
function makefunc(x) {
return function() {
return x;
}
}
var a = [makefunc(0), makefunc(1), makefunc(2)];
a[0](); [86]
a[1](); [87]
a[2](); [88]
8.5.3 Sharing Closure Variables Among Functions
function makeProperty(o, name, predicate) {
var value;
o["get" + name] = function() { return value; };
o["set" + name] = function(v) {
if (predicate && !predicate(v))
throw "set" + name + ": invalid value " + v;
else
value = v;
};
}
var o = {};
makeProperty(o, "Name", function(x) { return typeof x == "string"; });
o.setName("Frank");
o.getName() [89]
o.setName(123) [90]
o.getName() [91]
o.setName('Joe') [92]
o.getName() [93]
8.5.4 Breakpoints using Closures
function inspect(inspector, title) {
var expression, result;
if ("ignore" in arguments.callee) return;
while(true) {
var message = "";
if (title) message = title + "\n";
if (expression) message += "\n" + expression + " ==> " + result + "\n";
else expression = "";
message += "Enter an expression to evaluate:";
expression = prompt(message, expression);
if (!expression) return;
result = inspector(expression);
}
}
function factorial(n) {
var inspector = function(x) {
return eval(x);
}
inspect (inspector, "Entering factorial()");
var result = 1;
while (n > 1){
result = result * n;
n--;
inspect(inspector, "factorial() loop");
}
inspect(inspector, "Exiting factorial()");
return result;
}
inspect(function (x) {return eval(x);}, 'Hello') [94]
factorial(5); [95]
8.5.5 Function Constructor
var f = new Function("x", "y", "return x*y");
function f(x,y){
return x*y;
}
- Allows you to generate code dynamically.
- Slow.
- These functions do not use lexical scoping.
9 Object-Oriented JavaScript
- JavaScript implements objects using the idea of a
prototype, as opposed to classes.
- An object constructor (cf. factory pattern [96]) implements the “class”
function Rectangle(w, h){
this.width = w;
this.height = h;
}
var r1 = new Rectangle(2,3);
r1 [97]
9.1 Prototype
- Adding a function as a property would lead to each
instance having a copy of all functions.
- Instead, there is a prototype for each
constructor which contains all the properties every instance
gets.
function Rectangle(w, h){
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
}
var r1 = new Rectangle(2,3);
r1.area() [98]
- Thus, an object inherits properties from its
prototype object.
- Use
hasOwnProperty("area")
to determine if
"area" is not inherited.
- A prototype object can inherit from its own prototype
object, and so on.......
- The properties' values are not copied at creation
time. They are dynamically looked up at runtime.
- Look up happens only when reading the value of a
property. When writing, the object obtains its own copy of the
property, if inherited.
9.1.1 Inheritance Example
function object(o) {
function F() {};
F.prototype = o;
return new F();
}
var human = {
name: "Floyd",
age: 33,
sex: "Male",
}
var employee = object(human);
employee.salary = 100;
employee.name; [99]
human.name = 'Pink'; [100]
employee.name; [101]
employee.name = 'Blue'; [102]
human.name; [103]
9.1.2 Inheritance via Constructor Chaining
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() { return this.width * this.height; }
function PositionedRectangle(x, y, w, h) {
Rectangle.call(this, w, h);
this.x = x;
this.y = y;
}
PositionedRectangle.prototype = new Rectangle();
delete PositionedRectangle.prototype.width;
delete PositionedRectangle.prototype.height;
PositionedRectangle.prototype.constructor = PositionedRectangle;
PositionedRectangle.prototype.contains = function(x,y) {
return (x > this.x && x < this.x + this.width &&
y > this.y && y < this.y + this.height);
9.1.3 Extend a Type
- You can use the prototype to add to an existing type.
String.prototype.trim = function() {
return this.replace(
/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}
'---' + ' hello there '.trim() + '---' [104]
String.prototype.supplant = function (o){
return this.replace(/{([^{}]*)}/g,
function (a,b) {
return o[b];
}
);
};
var template = '<table border="{border}"' +
'<tr><th>Last</th><td>{last}</td></tr>' +
'<tr><th>First</th><td>{first}</td></tr>' +
'</table>';
var data = {
first: "Carl",
last: "Hollywood",
border: 2
};
template.supplant(data)
[105]
Object.prototype
Array.prototype
Function.prototype
Number.prototype
String.prototype
Boolean.prototype
9.1.4 Calling Overridden Methods
- Get to them via the
prototype
.
Rectangle.prototype.toString = function () {
return "[" + this.width + "," + this.height + "]";
}
PositionedRectangle.prototype.toString = function (){
return "(" + this.x + "," + this.y +") " +
Rectangle.prototype.toString.apply(this); }
9.1.5 Mixins
function borrowMethods(borrowFrom, addTo) {
var from = borrowFrom.prototype; var to = addTo.prototype;
for(m in from) { if (typeof from[m] != "function") continue; to[m] = from[m]; }
}
function GenericToString() {}
GenericToString.prototype.toString = function() {
var props = [];
for(var name in this) {
if (!this.hasOwnProperty(name)) continue;
var value = this[name];
var s = name + ":"
switch(typeof value) {
case 'function':
s += "function";
break;
case 'object':
if (value instanceof Array) s += "array"
else s += value.toString();
break;
default:
s += String(value);
break;
}
props.push(s);
}
return "{" + props.join(", ") + "}";
}
function GenericEquals() {}
GenericEquals.prototype.equals = function(that) {
if (this == that) return true;
var propsInThat = 0;
for(var name in that) {
propsInThat++;
if (this[name] !== that[name]) return false;
}
var propsInThis = 0;
for(name in this) propsInThis++;
if (propsInThis != propsInThat) return false;
return true;
}
borrowMethods(GenericEquals, Rectangle);
borrowMethods(GenericToString, Rectangle)
- Once an object implements all the methods defined by a
class/constructor it becomes an instance of that class!
- Known as duck typing [106].
9.1.6 Complex Numbers Example
function Complex(real, imaginary) {
this.x = real; this.y = imaginary; }
Complex.prototype.magnitude = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
};
Complex.prototype.negative = function() {
return new Complex(-this.x, -this.y);
};
Complex.prototype.add = function(that) {
return new Complex(this.x + that.x, this.y + that.y);
}
Complex.prototype.multiply = function(that) {
return new Complex(this.x * that.x - this.y * that.y,
this.x * that.y + this.y * that.x);
}
Complex.prototype.toString = function() {
return "{" + this.x + "," + this.y + "}";
};
Complex.prototype.equals = function(that) {
return this.x == that.x && this.y == that.y;
}
Complex.prototype.valueOf = function() { return this.x; }
Complex.sum = function (a, b) {
return new Complex(a.x + b.x, a.y + b.y);
};
Complex.product = function(a, b) {
return new Complex(a.x * b.x - a.y * b.y,
a.x * b.y + a.y * b.x);
};
Complex.ZERO = new Complex(0,0);
Complex.ONE = new Complex(1,0);
Complex.I = new Complex(0,1);
9.1.7 Private Members
- Simulate them using closures.
function ImmutableRectangle (w, h){
this.getWidth = function() {
return w;
};
this.getHeight = function() {
return h;
};
}
ImmutableRectangle.prototype.area() = function (){
return this.getWidth() * this.getHeight();
}
9.2 Common Methods: toString
- Like in Java, the
toString
property/method
can be defined to pretty print your object.
Circle.prototype.toString = function (){
return "[Circle of radius " + this.r + ", centered at("
+ this.x + ", " + this.y + ").]";
}
9.3 instanceof
- Use
instanceof
to compare to a constructor:
if (x instanceof Array) {
}
- Does not recognize duck typing. You must define
your own operator.
10 Modules and Namespaces
- Needed for libraries: JSAN [107].
- No namespaces, but use objects instead.
var jmvidal;
if (!jmvidal) jmvidal = {};
jmvidal.Lib590 = {};
jmvidal.Lib590.myfun1 = function (x) {
};
jmvidal.Lib590.myfun2 = function (x) {
}
11 Regular Expressions
URLs
- José M. Vidal, http://jmvidal.cse.sc.edu
- http://jmvidal.cse.sc.edu/talks/javascript/, http://jmvidal.cse.sc.edu/talks/javascript/
- JavaScript, http://jmvidal.cse.sc.edu/lib/flanagan06a.html
- JavaScript: The Good Parts, http://jmvidal.cse.sc.edu/lib/crockford08a.html
- taken, http://www.davidflanagan.com/javascript5/
- wikipedia:Javascript, http://www.wikipedia.org/wiki/Javascript
- by
itself, http://developer.mozilla.org/en/docs/About_JavaScript
- SpiderMonkey, http://developer.mozilla.org/en/docs/SpiderMonkey
- Rhino, http://www.mozilla.org/rhino/
- Chrome, http://www.google.com/chrome
- firefox 3.1, http://www.mozilla.com/en-US/firefox/all-beta.html
- 0.1 + 0.2, javascript:alert(0.1 + 0.2)
- 'steve'.length, javascript:alert('steve'.length)
- 'steve'.charAt(1), javascript:alert('steve'.charAt(1))
- 'steve'.substring(1,4), javascript:alert('steve'.substring(1,4))
- 'steve'.indexOf('e'), javascript:alert('steve'.indexOf('e'))
- Number('1.0') + Number('2'), javascript:alert(Number('1.0') + Number('2'))
- if (1) {'yes'} else {'no'}, javascript:if (1) {'yes'} else {'no'}
- if (0) {'yes'} else {'no'}, javascript:if (0) {'yes'} else {'no'}
- if (1 == 0) {'yes'} else {'no'}, javascript:if (1 == 0) {'yes'} else {'no'}
- 'What he said is ' + (1 == 0), javascript:'What he said is ' + (1 == 0)
- square(5);, javascript:alert(square(5))
- doublef(plusone,5), javascript:alert(doublef(plusone,5));
- a;, javascript:alert(a);
- var now = new
Date(), javascript:alert(new Date())
- m;, javascript:alert(m);
- xmas != solstice_plus_4, javascript:alert(xmas != solstice_plus_4)
- t;, javascript:alert(t)
- '1' == true, javascript: '1' == true
- var v = {x:1}; v == {x:1}, javascript:var v = {x:1}; v == {x:1}
- var v = {x:1}; v == v, javascript:var v = {x:1}; v == v
- '1' === true, javascript: '1' === true
- var v = {x:1}; v === {x:1}, javascript:var v = {x:1}; v === {x:1}
- var v = {x:1}; v === v, javascript:var v = {x:1}; v === v
- var p = {x:1,y:1}; 'y' in p, javascript:var p = {x:1,y:1}; 'y' in p
- var p = {x:1,y:1}; 'z' in p, javascript:var p = {x:1,y:1}; 'z' in p
- var d = new Date(); d instanceof Date, javascript:var d = new Date();d instanceof Date
- var d = new Date(); d instanceof Object, javascript:var d = new Date();d instanceof Object
- var d = new Date(); d instanceof Number, javascript:var d = new Date();d instanceof Number
- 1 + 2, javascript: 1 + 2
- '1' + '2', javascript: '1' + '2'
- '1' + 2, javascript: '1' + 2
- '11' < '2', javascript: '11' < '2'
- '11' < 2, javascript: '11' < 2
- 1 + 2 + ' blind mice', javascript: 1 + 2 + ' blind mice'
- 'blind mice=' + 1 + 3, javascript: 'blind mice=' + 1 + 3
- Run, javascript:var d = {x:1, y:2};for (var prop in d){alert(prop + ':' + d[prop]);}
- var d = new Date();
d.constructor==Date, javascript:var d =
new Date(); d.constructor==Date;
- var o={x:1,y:2};alert(o.toString());, javascript:var o={x:1,y:2};alert(o.toString());
- var now = new
Date();alert(now.valueOf());, javascript:var now = new
Date();alert(now.valueOf());
- var a = new Array();, javascript:var a = new Array();alert(a.length);
- var a = new Array(10);, javascript:var a = new Array(10);alert(a.length);
- var a = [4,5];, javascript:var a = [4,5];alert(a.length);
- var a = [4,5];, javascript:var a = [4,5]; a[10] = 3; alert(a.length);
- var a =[1,2,3];, javascript:var a =[1,2,3];alert(a.join('=='));
- var a=[1,2,3];, javascript:var a=[1,2,3];alert(a.reverse());
- var a=['beta','alpha','delta'];, javascript:var a=['beta','alpha','delta'];alert(a.sort());
- var a=[1,2,3,4];, javascript:var a=[1,2,3,4];alert(a.sort(function(x,y){return y-x;}));
- var a=[1,2,3];, javascript:var a=[1,2,3];alert(a.concat(4,5));
- a.concat([4,5]);, javascript:var a=[1,2,3];alert(a.concat([4,5]));
- a.concat([4,5],[6,7]);, javascript:var a=[1,2,3];alert(a.concat([4,5],[6,7]));
- a.concat(4,5,[6,[7,8]]);, javascript:var a=[1,2,3];alert(a.concat(4,5,[6,[7,8]]));
- var a=[1,2,3,4,5];, javascript:var a=[1,2,3,4,5];alert(a.slice(0,3));
- a.slice(3);, javascript:var a=[1,2,3,4,5];alert(a.slice(3));
- a.slice(1,-1);, javascript:var a=[1,2,3,4,5];alert(a.slice(1,-1));
- a.slice(-3,-1);, javascript:var a=[1,2,3,4,5];alert(a.slice(-3,-1));
- var a=[1,2,3,4,5,6,7,8];, javascript:var a=[1,2,3,4,5,6,7,8];alert(a.splice(4));
- var a=[1,2,3,4,5,6,7,8];, javascript:var a=[1,2,3,4,5,6,7,8];alert(a.splice(1,2));
- var a=[1,2,3,4,5,6,7,8];, javascript:var a=[1,2,3,4,5,6,7,8];alert(a.splice(2,4));
- getArguments(1,2,3), javascript:alert(getArguments(1,2,3))
- getArguments('hi', 2), javascript:alert(getArguments('hi',2))
- getArguments(), javascript:alert(getArguments())
- getCaller(), javascript:alert(getCaller())
- i;, javascript:alert(i)
- j;, javascript:alert(j)
- k;, javascript:alert(k)
- calculator.compute();, javascript:calculator.compute()
- calculator.result, javascript:alert(calculator.result)
- function foo(x,y,z){};, javascript:function foo(x,y,z){};alert(foo.length)
- getuid(), javascript:alert(getuid())
- hypotenuse(2,2);, javascript:alert(hypotenuse(2,2))
- x;, javascript:alert(x);
- f();, javascript:f();
- x;, javascript:alert(x);
- g();, javascript:g();
- a[0]();, javascript:alert(a[0]());
- a[1]();, javascript:alert(a[1]());
- a[2]();, javascript:alert(a[2]());
- o.getName(), javascript:alert(o.getName())
- o.setName(123), javascript:alert(o.setName(123))
- o.getName(), javascript:alert(o.getName())
- o.setName('Joe'), javascript:o.setName('Joe')
- o.getName(), javascript:alert(o.getName())
- inspect(function (x) {return eval(x);}, 'Hello'), javascript:inspect(function (x) {return eval(x);}, 'Hello')
- factorial(5);, javascript:alert(factorial(5));
- wikipedia:Factory_pattern, http://www.wikipedia.org/wiki/Factory_pattern
- r1, javascript:alert(r1)
- r1.area(), javascript:alert(r1.area())
- employee.name;, javascript:alert(employee.name)
- human.name = 'Pink';, javascript:alert(human.name = 'Pink')
- employee.name;, javascript:alert(employee.name)
- employee.name = 'Blue';, javascript:alert(employee.name = 'Blue')
- human.name;, javascript:alert(human.name)
- '---' + ' hello there '.trim() + '---', javascript:alert('---' + ' hello there '.trim() + '---')
- template.supplant(data)
, javascript:alert(template.supplant(data));
- wikipedia:Duck_typing, http://www.wikipedia.org/wiki/Duck_typing
- JSAN, http://www.openjsan.org
- wikipedia:Regular_expressions, http://www.wikipedia.org/wiki/Regular_expressions
- 'javascript'.search(/scr/i), javascript:alert('javascript'.search(/scr/i))
- 'javascript'.search(/joe/i), javascript:alert('javascript'.search(/joe/i))
- '1 plus 2 equals 3'.match(/\d+/g), javascript:alert('1 plus 2 equals 3'.match(/\d+/g))
This talk available at http://jmvidal.cse.sc.edu/talks/javascript/
Copyright © 2009 José M. Vidal
.
All rights reserved.
27 January 2009, 09:43AM